package edu.chinasoft.servlet;

import edu.chinasoft.domain.PageUnitForUser;
import edu.chinasoft.domain.User;
import edu.chinasoft.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 
 * @author 
 * @date 2020年1月19日:下午7:41:41
 * @version V1.0
 * @Description: 
 * 
*/
@WebServlet(name="myShowUserServlet",value="/servlet/showuserservlet")
public class  ShowUserServlet  extends HttpServlet {
	private static Logger logger = LoggerFactory.getLogger(ShowUserServlet.class);
	private UserService userService;
	/**
	 */
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		logger.debug(" ShowUserServlet >doGet start.......");
		response.setContentType("text/html;charset=utf-8");
		request.setCharacterEncoding("utf-8");
		//获取分页单位
		ServletContext servletContext = this.getServletContext();
		String initParameter = servletContext.getInitParameter("pageUnit");
		int pageUnit = Integer.parseInt(initParameter);
		//获取当前页
		String pageParameter = request.getParameter("currentPage");
		pageParameter = pageParameter==null?"1":pageParameter;
		int currentPage = Integer.parseInt(pageParameter);
		Map<String, Object> map = new HashMap<>();
		int setLimit = (currentPage-1)*pageUnit;
		map.put("setLimit",setLimit);
		map.put("pageUnit",pageUnit);
		WebApplicationContext wac = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
		UserService userServiceImp = wac.getBean("userService", UserService.class);
		this.userService = userServiceImp;
		PageUnitForUser pageUnitForUser = userService.getRecordNum();
		List<User> userList = userService.selectUnitUser(map);
		pageUnitForUser.setUserList(userList);
		pageUnitForUser.setPageUnit(pageUnit);
		pageUnitForUser.setCurrentPage(currentPage);

		//加到session域里
		HttpSession session = request.getSession();
		session.setAttribute("userPage", pageUnitForUser);
		
		response.sendRedirect(""+request.getContextPath()+"/showUser.jsp");
		
		logger.debug(" ShowUserServlet >doGet end.......");
	}
	
	/**
	 * 
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		logger.debug(" ShowUserServlet >doPost start.......");
		this.doGet(request, response);
		
		logger.debug(" ShowUserServlet >doPost end.......");
	}
	
}